namespace Todos.Application.TodoItems.Commands;

[AuthConfig(typeof(TodoItem), ResourceAccessType.RoleLimit, "Delete")]
public class DeleteTodoItemCommand : IRequest<ApiResult>, ICommand
{
    public long ListId { get; set; }

    public long[] ItemIds { get; set; } = [];
}

public class DeleteTodoItemCommandHandler(IRepository<TodoList> repository) : IRequestHandler<DeleteTodoItemCommand, ApiResult>
{    public async Task<ApiResult> Handle(DeleteTodoItemCommand request, CancellationToken cancellationToken)
    {
        var spec = new TodoListByIdSpec(request.ListId).And(new TodoListIncludeItemsSpec());
        var list = await repository.GetAsync(spec, cancellationToken);
        if (list == null)
        {
            return new ApiResult(ApiResultType.Error, "待办列表不存在");
        }

        foreach (var itemId in request.ItemIds)
        {
            list.RemoveItem(itemId);
        }

        await repository.UpdateAsync(list, cancellationToken);
        return new ApiResult(ApiResultType.Success, $"{request.ItemIds.Length}个待办项删除成功");
    }
}

public class DeleteTodoItemCommandValidator : AbstractValidator<DeleteTodoItemCommand>
{
    public DeleteTodoItemCommandValidator()
    {
        RuleFor(m => m.ListId).NotEmpty().WithMessage("待办列表Id不能为空");
    }
}
